<?php

namespace backend\helpers;

use backend\models\match\Match;
use Yii;


/**
 * Class ApiHelper
 * @package backend\helpers
 */
class ApiHelper
{
    /**
     * 校验签名
     */
    public static function checkSign($data)
    {
        if (!isset($data['sign']) || empty($data['sign'])) {
            return false;
        }
        $sign = $data['sign'];
        unset($data['sign']);

        ksort($data);
        $post_str = http_build_query($data);
        if (md5($post_str . Yii::$app->params['api:match:signkey']) == $sign) {
            return true;
        }

        Yii::error($post_str, 'api');
        return false;
    }

    /**
     * 请求参数校验
     * @param array $params
     * @return array
     */
    public static function verifyParams($params = [])
    {
        if (empty($params)) {
            return ['code' => 1];
        }

        $data = Yii::$app->request->getBodyParams();
        foreach ($params as $_param) {
            if (!isset($data[$_param]) || empty($data[$_param])) {
                return [
                    'code' => 0,
                    'msg' => '请求参数错误:' . $_param,
                ];
            }
        }

        return ['code'=>1];
    }

    /**
     * 获取推流地址
     * 如果不传key和过期时间，将返回不含防盗链的url
     * @param bizId 您在腾讯云分配到的bizid
     *        streamId 您用来区别不同推流地址的唯一id
     *        key 安全密钥
     *        time 过期时间 sample 2016-11-12 12:00:00
     * @return String url */
    public static function getPushUrl($bizId, $streamId, $key = null, $time = null){

        if($key && $time){
            $txTime = strtoupper(base_convert(strtotime($time),10,16));
            //txSecret = MD5( KEY + livecode + txTime )
            //livecode = bizid+"_"+stream_id  如 8888_test123456
            $livecode = $bizId."_".$streamId; //直播码
            $txSecret = md5($key.$livecode.$txTime);
            $ext_str = "?".http_build_query(array(
                    "bizid"=> $bizId,
                    "txSecret"=> $txSecret,
                    "txTime"=> $txTime
                ));
        }
        return "rtmp://".$bizId.".livepush.myqcloud.com/live/".$livecode.(isset($ext_str) ? $ext_str : "");
    }

    /**
     * 获取播放地址
     * @param bizId 您在腾讯云分配到的bizid
     *        streamId 您用来区别不同推流地址的唯一id
     * @return String url */
    public static function getPlayUrl($bizId, $streamId){
        $livecode = $bizId."_".$streamId; //直播码
        return array(
            "rtmp://".$bizId.".liveplay.myqcloud.com/live/".$livecode,
            "http://".$bizId.".liveplay.myqcloud.com/live/".$livecode.".flv",
            "http://".$bizId.".liveplay.myqcloud.com/live/".$livecode.".m3u8"
        );
    }

}






